/**
 * Module dependencies.
 */
const express = require('express')
const bodyParser = require('body-parser')
const winston = require('winston')
const morgan = require('morgan')
const cors = require('cors')

const _init = require('./middleware/utils')
const _conf = require('./configs/configure')

const app = express()

// winston logger with console transport only
winston.configure({
  transports: [
    new winston.transports.Console({
      level: 'debug',
      format: winston.format.combine(
        winston.format.colorize({ all: true }),
        winston.format.splat(),
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.printf(({ level, message, timestamp }) => {
          return `[${timestamp}] [${level}] ${message}`
        })
      )
    })
  ]
})

if (app.get('env') === 'production') {
  winston.info('running in production mode !')
  app.use(morgan('tiny', {
    stream: { write: msg => winston.info(msg.trim()) }
  }))
  winston.add(
    new winston.transports.File({
      filename: 'error.log',
      level: 'error',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.splat(),
        winston.format.json()
      )
    })
  )
  winston.add(
    new winston.transports.File({
      filename: 'combine.log',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.splat(),
        winston.format.json()
      )
    })
  )
}

if (app.get('env') === 'development') {
  winston.info('running in development mode !')
  app.use(morgan('dev', {
    stream: { write: msg => winston.info(msg.trim()) }
  }))
}

app.use(bodyParser.json())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.use(cors({
  origin: _conf.cors.origin,
  allowedHeaders: [
    'Content-Type',
    'Content-Length',
    'Authorization',
    'Accept',
    'X-Requested-With',
    'yourHeaderFeild'
  ],
  methods: [
    "POST",
    "PATCH",
    "GET",
    "OPTIONS",
    "PUT",
    "DELETE",
    "HEAD"
  ],
  credentials: true,
  optionsSuccessStatus: 200,
  preflightContinue: false
}))
// app.all('*', (req, res, next) => {
//   res.header('Access-Control-Allow-Origin', 'http://192.168.1.171:20001');
//   res.header('Access-Control-Allow-Headers',
//     'content-type, Content-Length, Authorization, Origin, Accept, X-Requested-With, yourHeaderFeild');
//   res.header('Access-Control-Allow-Methods',
//     'POST, PATCH, GET, OPTIONS, PUT, DELETE, HEAD');
//   res.header('Access-Control-Allow-Credentials', true);
//   res.header("X-Powered-By", " 3.2.1")
//   req.header("Content-Type", "application/json;charset=utf-8")
//   next()
// })

const exclusion_url_list = []
app.use((req, res, next) => {
  // var url = req.originalUrl
  // console.log(url)
  // if (exclusion_url_list.includes(url))
    return next()
  // return res.status(403).json({})
})

app.use('/main', require('./routes/index'));   // Ending symbols for app.set and app.use !

(async () => {
  try {
    // listen http
    _init.listenHTTP(app)

    // init mongoose
    _init.initMongoose()
  } catch (e) {
    winston.error('Initialization failure !', e)
  }
})()
